package com.jic.member.impl;

import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.rest.UserSysDeptApi;
import com.jic.member.constant.consist.ResponseCode;
import com.jic.member.exception.AppRuntimeException;
import com.jic.member.mapper.TLabelMapper;
import com.jic.member.mapper.TLabelMerchantRelationMapper;
import com.jic.member.entity.TLabel;
import com.jic.member.entity.TLabelMerchantRelation;
import com.jic.member.request.TLabelMerchantRelationRequest;
import com.jic.member.request.TLabelRequest;
import com.jic.member.response.TLabelResponse;
import com.jic.member.service.TLabelMerchantRelationService;
import com.jic.manager.response.SysDeptResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class TLabelMerchantRelationServiceImpl implements TLabelMerchantRelationService {

    @Resource
    private TLabelMerchantRelationMapper mapper;


    @Resource
    private TLabelMapper tLabelMapper;

    @Resource
    private UserSysDeptApi sysDeptApi;




    /**
     * 新增记录
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult save(TLabelMerchantRelationRequest request) {
        try {
            log.info("开始进入保存标签开放记录，入参 = {}", JSONObject.toJSONString(request));
            if (CollectionUtils.isNotEmpty(request.getAdminOperate().getMerchantIds())) {
                //开放给商家
                request.getAdminOperate().getMerchantIds().forEach(item -> {
                    //保存开放记录
                    HashMap map=new HashMap();
                    map.put("businessId",item);
                    map.put("deptType",2);
                    List<SysDeptResponse> deptIdByBusinessId = sysDeptApi.getDeptIdByBusinessId(map);
                    if(CollectionUtils.isNotEmpty(deptIdByBusinessId)){
                        TLabelMerchantRelation tLabelMerchantRelation = new TLabelMerchantRelation();
                        tLabelMerchantRelation.setLabelId(request.getLabelId());
                        tLabelMerchantRelation.setCreator(request.getAdminOperate().getOperator());
                        tLabelMerchantRelation.setDeptId(deptIdByBusinessId.get(0).getId());
                        tLabelMerchantRelation.setDeleteFlag(0);
                        mapper.insert(tLabelMerchantRelation);
                    }
                });
            }
            //开放给店铺
            if (CollectionUtils.isNotEmpty(request.getAdminOperate().getStoreIds())) {
                //保存开放记录
                request.getAdminOperate().getStoreIds().forEach(item -> {
                    HashMap map=new HashMap();
                    map.put("businessId",item);
                    map.put("deptType",3);
                    List<SysDeptResponse> deptIdByBusinessId = sysDeptApi.getDeptIdByBusinessId(map);
                    //保存开放记录
                    if(CollectionUtils.isNotEmpty(deptIdByBusinessId)){
                        TLabelMerchantRelation tLabelMerchantRelation = new TLabelMerchantRelation();
                        tLabelMerchantRelation.setLabelId(request.getLabelId());
                        tLabelMerchantRelation.setCreator(request.getAdminOperate().getOperator());
                        tLabelMerchantRelation.setDeptId(deptIdByBusinessId.get(0).getId());
                        tLabelMerchantRelation.setDeleteFlag(0);
                        mapper.insert(tLabelMerchantRelation);
                    }
                });
            }
            //修改标签状态
            TLabel tLabel = new TLabel();
            tLabel.setId(request.getLabelId());
            tLabel.setStatus(1);
            tLabelMapper.updateByPrimaryKey(tLabel);
            TLabel tLabel1 = new TLabel();
            tLabel1.setPid(request.getLabelId());
            tLabel1.setDeleteFlag(0);
            List<TLabel> tLabels = tLabelMapper.selectBySelective(tLabel1);
            if (CollectionUtils.isNotEmpty(tLabels)) {
                tLabels.forEach(item -> {
                    TLabel tLabel2 = new TLabel();
                    tLabel2.setId(item.getId());
                    tLabel2.setStatus(1);
                    tLabelMapper.updateByPrimaryKey(tLabel2);
                });
            }
        } catch (Exception e) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "保存失败");
        }
        return RestResult.success(Boolean.TRUE);
    }


    /**
     * 保存或修改记录信息
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:09
     */
    @Override
    public int saveOrUpdate(TLabelMerchantRelation request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKey(request);
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.insertSelective(request);
                if (flag == 1) {
                    return 1;
                } else {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }

    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(TLabelMerchantRelation request) {
        int flag = mapper.deleteByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
        }
    }


    /**
     * 逻辑删除记录
     *
     * @param request 含有主键的逻辑删除实体类
     * @return int 是否逻辑删除成功
     */
    @Override
    public int deleteByPrimaryKeyLogically(TLabelMerchantRelation request) {
        request.setDeleteFlag(1);
        int flag = mapper.updateByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult updateByPrimaryKeySelective(TLabelMerchantRelationRequest request) {
        try {
            log.info("开始进入保存标签开放记录，入参 = {}", JSONObject.toJSONString(request));
            //收回商家标签
            if (CollectionUtils.isNotEmpty(request.getAdminOperate().getMerchantIds())) {
                request.getAdminOperate().getMerchantIds().forEach(item -> {
                    HashMap map=new HashMap();
                    map.put("businessId",item);
                    map.put("deptType",2);
                    List<SysDeptResponse> deptIdByBusinessId = sysDeptApi.getDeptIdByBusinessId(map);
                    if(CollectionUtils.isNotEmpty(deptIdByBusinessId)){
                        deptIdByBusinessId.forEach(item1->{
                            TLabelMerchantRelation tLabelMerchantRelation = new TLabelMerchantRelation();
                            tLabelMerchantRelation.setDeleteFlag(0);
                            tLabelMerchantRelation.setLabelId(request.getLabelId());
                            tLabelMerchantRelation.setDeptId(item1.getId());
                            List<TLabelMerchantRelation> tLabelMerchantRelationList = mapper.selectBySelective(tLabelMerchantRelation);
                            if(CollectionUtils.isNotEmpty(tLabelMerchantRelationList)){
                                tLabelMerchantRelationList.forEach(item2->{
                                    //从商家店铺收回标签
                                    TLabelMerchantRelation tLabelMerchantRelation1 = new TLabelMerchantRelation();
                                    tLabelMerchantRelation1.setId(item2.getId());
                                    mapper.deleteByPrimaryKey(tLabelMerchantRelation1);
                                });
                            }
                        });
                    }
                });
            }
            //收回店铺标签
            if (CollectionUtils.isNotEmpty(request.getAdminOperate().getStoreIds())) {
                request.getAdminOperate().getStoreIds().forEach(item -> {
                    HashMap map=new HashMap();
                    map.put("businessId",item);
                    map.put("deptType",3);
                    List<SysDeptResponse> deptIdByBusinessId = sysDeptApi.getDeptIdByBusinessId(map);
                    if(CollectionUtils.isNotEmpty(deptIdByBusinessId)){
                        deptIdByBusinessId.forEach(item1->{
                            TLabelMerchantRelation tLabelMerchantRelation = new TLabelMerchantRelation();
                            tLabelMerchantRelation.setDeleteFlag(0);
                            tLabelMerchantRelation.setLabelId(request.getLabelId());
                            tLabelMerchantRelation.setDeptId(item1.getId());
                            List<TLabelMerchantRelation> tLabelMerchantRelationList = mapper.selectBySelective(tLabelMerchantRelation);
                            if(CollectionUtils.isNotEmpty(tLabelMerchantRelationList)){
                                tLabelMerchantRelationList.forEach(item2->{
                                    //从商家店铺收回标签
                                    TLabelMerchantRelation tLabelMerchantRelation1 = new TLabelMerchantRelation();
                                    tLabelMerchantRelation1.setId(item2.getId());
                                    mapper.deleteByPrimaryKey(tLabelMerchantRelation1);
                                });
                            }
                        });
                    }
                });
            }
            //修改标签状态
            TLabel tLabel = new TLabel();
            tLabel.setId(request.getLabelId());
            tLabel.setStatus(2);
            tLabelMapper.updateByPrimaryKey(tLabel);
            TLabel tLabelThird = new TLabel();
            tLabelThird.setPid(request.getLabelId());
            tLabelThird.setDeleteFlag(0);
            List<TLabel> tLabels = tLabelMapper.selectBySelective(tLabelThird);
            if (CollectionUtils.isNotEmpty(tLabels)) {
                tLabels.forEach(item4 -> {
                    TLabel tLabel2 = new TLabel();
                    tLabel2.setId(item4.getId());
                    tLabel2.setStatus(2);
                    tLabelMapper.updateByPrimaryKey(tLabel2);
                });
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
        }
        return RestResult.success(Boolean.TRUE);
    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public TLabelMerchantRelation getByPrimaryKey(TLabelMerchantRelation request) {
        return mapper.selectByPrimaryKey(request);
    }


    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<TLabelMerchantRelation> listAllRecord(TLabelMerchantRelation request) {
        //分页处理
        request.setDeleteFlag(0);
        return mapper.selectBySelective(request);
    }

    @Override
    public PageResult<TLabelResponse> listPageBySelective(TLabelRequest request, Page page) {
        //计算下标
        int startIndex = (page.getStart() - 1) * page.getLimit();
        //查询已经分配给商家店铺的三级标签
        request.setDeptId(request.getAdminOperate().getDeptId());
        List<TLabel> list = mapper.listPageBySelective(request, startIndex, page.getLimit());
        List<TLabelResponse> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(item -> {
                TLabelResponse tLabelResponse = new TLabelResponse();
                BeanUtils.copyProperties(item, tLabelResponse);
                tLabelResponse.setId(item.getId());
                if (null != item.getDeptId()) {
                    RestResult<String> restResult = sysDeptApi.queryDeptNameById(item.getDeptId());
                    if (restResult != null) {
                        tLabelResponse.setDeptName(restResult.getData());
                    }
                }
                //查询所有二级标签
                TLabel tLabel = new TLabel();
                tLabel.setId(item.getPid());
                TLabel tSecondLabel = tLabelMapper.selectByPrimaryKey(tLabel);
                if (tSecondLabel != null) {
                    tLabelResponse.setSecondLabelName(tSecondLabel.getLabelName());
                    //查询一级标签
                    TLabel tLabel1 = new TLabel();
                    tLabel1.setId(tSecondLabel.getPid());
                    TLabel tFirstLabel = tLabelMapper.selectByPrimaryKey(tLabel1);
                    if (tFirstLabel != null) {
                        tLabelResponse.setFirstLabelName(tFirstLabel.getLabelName());
                    }
                }
                responseList.add(tLabelResponse);
            });
        }
        //分组排序处理
        List<TLabelResponse> responseList1 = new ArrayList<>();
        Map<String, String> tLabelMap = new HashMap<String, String>();
        if (CollectionUtils.isNotEmpty(responseList)) {
            for (TLabelResponse tLabelResponse : responseList) {
                tLabelMap.put(tLabelResponse.getSecondLabelName(), "");
            }
            for (String key : tLabelMap.keySet()) {
                for (TLabelResponse tLabelResponse : responseList) {
                    if (key.equals(tLabelResponse.getSecondLabelName())) {
                        responseList1.add(tLabelResponse);
                    }
                }
            }
        }
        Long count = mapper.listPageBySelectiveCount(request);
        PageResult<TLabelResponse> result = new PageResult<>();
        result.setTotal(count);
        result.setRows(responseList1);
        return result;
    }
}
